import React, { useEffect, useState } from 'react';
import TreeControlled from '@/components/blocks/TreeControlled';
import { Tabs, Spin } from 'antd';
import { useRequest } from '@umijs/hooks';
import { getFunctional } from '../../service';
import { cloneDeep } from 'lodash';

export default function Step2(props) {
  const { checkedRoleKeys, setCheckedRoleKeys, loading: roleLoading, data: roleData } = props;
  const { data = [], loading } = useRequest(() =>
    getFunctional({ competence: roleData.competence }),
  );

  const [leafNodeObj, setLeafNodeObj] = useState({});
  const [newKey, setNewKey] = useState([]);

  useEffect(() => {
    if (data && data.length) {
      // 过滤 普通航班监控-航延补偿页面，不正常航班监控-航延补偿页面，服务补偿子平台-补偿详情
      for (let item of data) {
        if (item.key === "W" && item.title === "WEB端") {
          for (let child of item.children) {
            if (child.title === "航班监控") {
              child.children = child.children.filter(item => item.title !== '航延补偿页面');
            }
            if (child.title === "不正常航班") {
              child.children = child.children.filter(item => item.title !== '航延补偿页面');
            }
            if (child.title === "服务补偿") {
              child.children = child.children.filter(item => item.title !== '补偿详情' && item.title !== '补偿单审核详情' && item.title !== '箱包补偿单详情');
            }
          }
        }
      };
      data.map(item => getLeafNode(item, []));
      let deleteKey = []
      checkedRoleKeys.map(item => {
        if (leafNodeObj[item]) {
          deleteKey = deleteKey.concat(checkedRoleKeys.filter(delKey => (leafNodeObj[item].indexOf(delKey) + 1)));
        }
      })
      setNewKey(checkedRoleKeys.filter(item => !(deleteKey.indexOf(item) + 1)));
    }
  }, [checkedRoleKeys, data]);

  const getLeafNode = (data, fArr = []) => {
    if (!data.children) {
      const leafObj = {};
      leafObj[data.key] = cloneDeep(fArr);
      setLeafNodeObj(Object.assign(leafNodeObj, leafObj));
    } else {
      fArr.push(data.key);
      data.children.map(item => {
        getLeafNode(item, fArr);
      })
    }
  }

  return (
    <div style={{ paddingLeft: 24, height: 300, overflow: 'auto' }}>
      <Tabs>
        <Tabs.TabPane tab="功能权限" key="1">
          <Spin spinning={loading || roleLoading} style={{ minHeight: 30 }}>
            <TreeControlled
              checkable
              data={data || []}
              checkedKeys={newKey}
              setCheckedKeys={setCheckedRoleKeys}
            />
          </Spin>
        </Tabs.TabPane>
      </Tabs>
    </div>
  );
}
